package com.heima.common.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/****
 * 用户会话请求对象处理
 */
public class RequestContextUtil {

    /***
     * 根据指定key获取请求头数据
     */
    public static String getHeader(String key) {
        //获取当前线程对应的HttpServletRequet和HttpServletResponse
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取指定的key
        HttpServletRequest request = requestAttributes.getRequest();
        String header = request.getHeader(key);
        return header;
    }

    /***
     * 获取token，并解析token
     */
    public static Map<String, Object> token() {
        //1)获取令牌
        String token = getHeader("token");

        //2)解析令牌
        return Jwtutil.parse(token);
    }

    /**
     * 获取Token中指定的key
     *
     * @param key
     * @return
     */
    public static <T> T get(String key) {
        //1)获取token，解析token‘
        Map<String, Object> tokenMap = token();
        //2)获取token中指定的key
        return (T) tokenMap.get(key);
    }
}